<template>
  <view class="return-list-page">
    <view
      class="return-card"
      v-for="item in returnList"
      :key="item.return_code"
    >
      <view class="card-header">
        <view class="status-tag" :class="getStatusClass(item.return_state_name)">
          {{ item.return_state_name }}
        </view>
        <view class="bill-code">{{ item.return_code }}</view>
        <view class="card-menu">···</view>
      </view>
      
      <!-- 退库单名称 -->
      <view class="info-section">
        <view class="info-row">
          <text class="info-label">退库单名称</text>
        </view>
        <view class="info-value">{{ item.return_name || '' }}</view>
      </view>
      
      <!-- 退库人、退库日期、退库位置 -->
      <view class="info-grid">
        <view class="grid-item">
          <text class="info-label">退库人</text>
          <text class="info-value">{{ item.return_user_name || '' }}</text>
        </view>
        <view class="grid-item">
          <text class="info-label">退库日期</text>
          <text class="info-value">{{ item.f_return_date || '' }}</text>
        </view>
        <view class="grid-item">
          <text class="info-label">退库位置</text>
          <text class="info-value">{{ item.return_location_name || item.return_location || '' }}</text>
        </view>
      </view>
      
			<!-- 底部操作按钮 -->
			<view class="action-row">
				<up-button 
					type="primary" 
					plain 
					size="large"
					text="详情"
					@click="onDetail(item)"
					:customStyle="btnStyle"
				></up-button>
				
				<up-button 
					type="primary" 
					plain 
					size="large"
					text="审核记录"
					@click="goToAudit(item)"
					:customStyle="btnStyle"
				></up-button>
				
				<!-- 待审核或驳回状态：修改、删除 -->
				<up-button 
					v-if="item.return_state_name === '待审核' || item.return_state_name === '驳回'"
					type="primary" 
					plain 
					size="large"
					text="修改"
					@click="onEdit(item)"
					:customStyle="btnStyle"
				></up-button>
				
				<!-- 待审核状态：审核 -->
				<up-button 
					v-if="item.return_state_name === '待审核'"
					type="primary" 
					plain 
					size="large"
					text="审核"
					@click="onAudit(item)"
					:customStyle="btnStyle"
				></up-button>
				
				<!-- 待审核或驳回状态：删除 -->
				<up-button 
					v-if="item.return_state_name === '待审核' || item.return_state_name === '驳回'"
					type="error" 
					plain 
					size="large"
					text="删除"
					@click="onDelete(item)"
					:customStyle="btnStyle"
				></up-button>
				
				<!-- 审核通过状态：反审、签收 -->
				<up-button 
					v-if="item.return_state_name === '审核通过'"
					type="warning" 
					plain 
					size="large"
					text="反审"
					@click="onUnAudit(item)"
					:customStyle="btnStyle"
				></up-button>
				
				<up-button 
					v-if="item.return_state_name === '审核通过'"
					type="success" 
					plain 
					size="large"
					text="签收"
					@click="onReceive(item)"
					:customStyle="btnStyle"
				></up-button>
			</view>
    </view>
  </view>
</template>

<script setup>
import { defineProps } from "vue";
import http from "@/api/request";

// 在script中定义按钮样式
const btnStyle = {
  flex: 1,
  minWidth: '150rpx',
  height: '90rpx',
  fontSize: '34rpx',
  margin: '0 10rpx'
}

// 通过 props 传入 returnList
const props = defineProps({
  returnList: {
    type: Array,
    default: () => []
  }
});

function getStatusClass(status) {
  if (status === '完成') return 'status-done';
  if (status === '审核通过') return 'status-pass';
  if (status === '驳回') return 'status-reject';
  if (status === '待审核') return 'status-pending';
  return 'status-other';
}

function goToAudit(item) {
  uni.navigateTo({
    url: `/pages/assetReturn/auditRecord?returnCode=${item.return_code}`
  });
}

function onDetail(item) {
  uni.navigateTo({
    url: `/pages/assetReturn/detail?returnCode=${item.return_code}`
  });
}

function onEdit(item) {
  uni.navigateTo({
    url: `/pages/assetReturn/add?returnCode=${item.return_code}`
  });
}

function onAudit(item) {
  // 跳转到详情页面并带上审核标识
  uni.navigateTo({
    url: `/pages/assetReturn/detail?returnCode=${item.return_code}&mode=audit`
  });
}

function onUnAudit(item) {
  // 反审逻辑
  uni.showModal({
    title: '反审确认',
    content: `确定反审退库单 ${item.return_code} 吗？`,
    cancelText: '取消',
    confirmText: '确定',
    success: (res) => {
      if (res.confirm) {
        // 调用反审接口
        submitUnAudit(item.return_code);
      }
    }
  });
}

// 提交反审结果
function submitUnAudit(returnCode) {
  uni.showLoading({
    title: '提交中...'
  });
  
  const data = { 
    "pageCode": "assetreturn", 
    "params": { 
      "args": [ 
        { 
          "name": "interfaceCode", 
          "value": "assetreturn.approveAssetReturnOrder" 
        }, 
        { 
          "name": "assetReturnCode", 
          "value": returnCode 
        }, 
        { 
          "name": "auditState", 
          "value": "PENDING_REVIEW" 
        } 
      ] 
    }, 
    "methodName": "approveAssetReturnOrder" 
  };
  
  http.post("/api/module/Invoke", data).then((res) => {
    uni.hideLoading();
    if (res.isSuccess) {
      uni.showToast({
        title: '反审成功',
        icon: 'success'
      });
      
      // 延迟一下再刷新页面，确保提示显示完成
      setTimeout(() => {
        // 使用全局事件通知父组件刷新数据
        uni.$emit('data-changed');
      }, 1000);
    } else {
      uni.showToast({
        title: res.error || '操作失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    uni.hideLoading();
    console.error('反审操作失败:', err);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  });
}

function onReceive(item) {
  // 签收逻辑
  uni.showModal({
    title: '签收确认',
    content: `确定签收退库单 ${item.return_code} 吗？`,
    cancelText: '取消',
    confirmText: '确定',
    success: (res) => {
      if (res.confirm) {
        // 调用签收接口
        submitReceive(item.return_code);
      }
    }
  });
}

// 提交签收结果
function submitReceive(returnCode) {
  uni.showLoading({
    title: '提交中...'
  });
  
  const data = { 
    "pageCode": "assetreturn", 
    "params": { 
      "args": [ 
        { 
          "name": "interfaceCode", 
          "value": "assetreturn.approveAssetReturnOrder" 
        }, 
        { 
          "name": "assetReturnCode", 
          "value": returnCode 
        }, 
        { 
          "name": "auditState", 
          "value": "COMPLETED" 
        } 
      ] 
    }, 
    "methodName": "approveAssetReturnOrder" 
  };
  
  http.post("/api/module/Invoke", data).then((res) => {
    uni.hideLoading();
    if (res.isSuccess) {
      uni.showToast({
        title: '签收成功',
        icon: 'success'
      });
      
      // 延迟一下再刷新页面，确保提示显示完成
      setTimeout(() => {
        // 使用全局事件通知父组件刷新数据
        uni.$emit('data-changed');
      }, 1000);
    } else {
      uni.showToast({
        title: res.error || '操作失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    uni.hideLoading();
    console.error('签收操作失败:', err);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  });
}

function onDelete(item) {
  // 删除逻辑
  uni.showModal({
    title: '删除确认',
    content: `确定删除退库单 ${item.return_code} 吗？`,
    cancelText: '取消',
    confirmText: '确定',
    success: (res) => {
      if (res.confirm) {
        // 显示加载中
        uni.showLoading({
          title: '删除中...'
        });
        
        // 构建请求参数
        const data = { 
          "pageCode": "assetreturn", 
          "params": { 
            "args": [ 
              { 
                "name": "interfaceCode", 
                "value": "assetreturn.softDeleteAssetReturnOrder" 
              }, 
              { 
                "name": "assetReturnCode", 
                "value": item.return_code 
              } 
            ] 
          }, 
          "methodName": "softDeleteAssetReturnOrder" 
        };
        
        // 调用删除接口
        http.post("/api/module/Invoke", data).then((res) => {
          uni.hideLoading();
          if (res.isSuccess) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
            
            // 延迟一下再刷新页面，确保提示显示完成
            setTimeout(() => {
              // 使用全局事件通知父组件刷新数据
              uni.$emit('data-changed');
            }, 1000);
          } else {
            uni.showToast({
              title: res.error || '删除失败',
              icon: 'none'
            });
          }
        }).catch(err => {
          uni.hideLoading();
          console.error('删除操作失败:', err);
          uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
          });
        });
      }
    }
  });
}
</script>

<style scoped>
.return-list-page {
  background: #f5f5f5;
  min-height: 100vh;
  padding: 20rpx 0;
}

.return-card {
  background: #fff;
  border-radius: 16rpx;
  margin: 20rpx;
  padding: 24rpx 28rpx 18rpx 28rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.status-tag {
  font-size: 24rpx;
  padding: 4rpx 16rpx;
  border-radius: 8rpx;
  margin-right: 16rpx;
  background: #e6f9f0;
  color: #2ecc71;
}

.status-done {
  background: #e6f9f0;
  color: #2ecc71;
}

.status-pass {
  background: #e6f7ff;
  color: #1890ff;
}

.status-reject {
  background: #fff2e8;
  color: #fa541c;
}

.status-pending {
  background: #f9f0ff;
  color: #722ed1;
}

.status-other {
  background: #f5f5f5;
  color: #666;
}

.bill-code {
  font-weight: bold;
  font-size: 30rpx;
  flex: 1;
}

.card-menu {
  font-size: 36rpx;
  color: #bbb;
}

/* 信息区域样式 */
.info-section {
  padding: 10rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-row {
  margin-bottom: 8rpx;
}

.info-label {
  color: #999;
  font-size: 26rpx;
}

.info-value {
  color: #333;
  font-size: 30rpx;
  font-weight: 500;
}

/* 网格布局 */
.info-grid {
  display: flex;
  padding: 16rpx 0;
  /* border-bottom: 1px solid #f0f0f0; */
}

.grid-item {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.grid-item .info-label {
  margin-bottom: 8rpx;
}

/* 操作按钮样式 */
.action-row {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-top: 40rpx;
  padding-top: 30rpx;
  border-top: 2rpx solid #f0f0f0;
  gap: 20rpx;
}

.action-btn {
  flex: 1;
  min-width: 120rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
  color: #2979ff;
  background-color: #fff;
  border: 2rpx solid #2979ff;
  border-radius: 15rpx;
  text-align: center;
  padding: 0 10rpx;
  box-sizing: border-box;
}

.action-btn:active {
  background-color: #f0f7ff;
  opacity: 0.8;
}
</style>